//
//  WBRefreshControl.swift
//  glzbowei
//
//  Created by 高伦展 on 2018/2/11.
//  Copyright © 2018年 glz. All rights reserved.
//

import UIKit

private let WBRefreshControlOffset:CGFloat = -60

//自定义刷新控件 - 负责处理刷新逻辑
class WBRefreshControl: UIRefreshControl {

    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopAnimation()
    }
    
    override func beginRefreshing() {
        super.beginRefreshing()
        
        refreshView.startAnimation()
    }
    
    //KVO监听方法
    /*
     1.始终待在屏幕上
     2.下拉的时候，frame 是 y 一直变小 ， 相反（向上推）一直变大
     3.默认的y 是 0
     */
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if frame.origin.y > 0{
            return 
        }
        
        if isRefreshing {
            refreshView.startAnimation()
            return 
        }
        
        if frame.origin.y < (WBRefreshControlOffset) && !refreshView.rotateFlag{
            print("反过来")
            refreshView.rotateFlag = true
     
        }else if frame.origin.y >= (WBRefreshControlOffset) && refreshView.rotateFlag{
            print("转过来")
            refreshView.rotateFlag = false
        }
        
        //print(frame)
    }
    
    override init() {
        super.init()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    private func setupUI(){
        // 0. 清空转轮颜色
        tintColor = UIColor.clear
        
        //添加控件
        addSubview(refreshView)
        
        refreshView.snp.makeConstraints { (make) in
            make.center.equalTo(self.snp.center)
            make.size.equalTo(refreshView.bounds.size)
        }
        
        DispatchQueue.global().async {
            // code
            DispatchQueue.main.async {
                // 主线程中
                //使用kvo监听位置变化
                self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
            }
        }
        
    }
    
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
     //懒加载
    private lazy var refreshView = WBRefreshView.refreshView()
}



//刷新视图 - 负责处理‘动画显示’
class WBRefreshView:UIView{
    
    //旋转标记
    var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }
    
    @IBOutlet weak var loadingIconView: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipIconView: UIImageView!
    
    //从XIB加载 视图
    class func refreshView() -> WBRefreshView{
    
        //推荐使用UINib 的方法加载
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        
        return nib.instantiate(withOwner: nil, options: nil).last as! WBRefreshView
    }
    
    //旋转图标动画
    func rotateTipIcon(){
        
        var angle = CGFloat(M_PI)
        angle += rotateFlag ? -0.0000001 : 0.0000001
        
        //旋转动画，特点：顺时针优先 + ‘就近原则’
        UIView.animate(withDuration: 0.5) {
            if self.tipIconView != nil{
                self.tipIconView.transform = self.tipIconView.transform.rotated(by: CGFloat(angle))
            }
        }
    }
    
    func startAnimation(){
        tipView.isHidden=true
        
        let key = "transform.rotation"
        if loadingIconView.layer.animation(forKey: key) != nil{
            return
        }
        
        let anim = CABasicAnimation(keyPath: key)
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.isRemovedOnCompletion = false
        
        loadingIconView.layer.add(anim, forKey: nil)
    }
    
     func stopAnimation(){
        
        tipView.isHidden=false
        
        loadingIconView.layer.removeAllAnimations()
    }
}
